const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors');
const path = require('path');

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// 路由
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// TTS API 端点
app.post('/api/tts', async (req, res) => {
  try {
    const { text, voice = 'zh-CN-XiaoxiaoNeural' } = req.body;
    
    // 这里可以集成真实的TTS服务，如Azure Speech Services
    // 目前返回模拟的音频数据
    const mockAudioData = {
      audioUrl: '/audio/sample.mp3',
      duration: text.length * 0.1, // 估算时长
      text: text
    };
    
    res.json(mockAudioData);
  } catch (error) {
    res.status(500).json({ error: 'TTS生成失败' });
  }
});

// WebSocket 连接处理
io.on('connection', (socket) => {
  console.log('用户已连接:', socket.id);
  
  socket.on('speak', async (data) => {
    try {
      const { text } = data;
      
      // 生成TTS音频
      const ttsResponse = await fetch('http://localhost:3000/api/tts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text })
      });
      
      const audioData = await ttsResponse.json();
      
      // 发送音频数据给客户端
      socket.emit('audioReady', audioData);
      
      // 触发口型同步
      socket.emit('startSpeaking', { text, duration: audioData.duration });
      
    } catch (error) {
      socket.emit('error', { message: '语音生成失败' });
    }
  });
  
  socket.on('disconnect', () => {
    console.log('用户已断开连接:', socket.id);
  });
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});
